package com.spzx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.common.security.annotation.InnerAuth;
import com.spzx.product.api.domain.Brand;
import com.spzx.service.BrandService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/brand")
@Tag(name = "品牌接口管理")
public class BrandController extends BaseController {
    @Autowired
    BrandService brandService;

    @GetMapping("/list")
    @Operation(summary = "查询品牌列表")
    public TableDataInfo getBrandList(Brand brand) {
        startPage();
        List<Brand> list = brandService.getBrandList(brand);
        TableDataInfo tableDataInfo = new TableDataInfo(list, brandService.list().size());
        return tableDataInfo;
    }
    @InnerAuth
    @GetMapping("/innerList")
    @Operation(summary = "内部接口:查询品牌列表")
    public R<List<Brand>> getBrandAll(){
        List<Brand> list = brandService.list();
        return R.ok(list);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询品牌详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(brandService.getById(id));
    }

    @PutMapping("/save")
    @Operation(summary = "新增或更新品牌信息")
    public AjaxResult insertBrand( Brand brand) {
        String brandName = brand.getName();
        if (brandName == null) {
            return AjaxResult.error("名称不能为空");
        }
        if (brandService.getOne(Wrappers.lambdaQuery(Brand.class).eq(Brand::getName, brandName)) != null) {
            return AjaxResult.error("该品牌已经存在");
        }
        boolean b = brandService.save(brand);
        return AjaxResult.success(b);
    }

    @PutMapping("/update")
    @Operation(summary = "更新品牌信息")
    public AjaxResult updateBrand(@RequestBody @Validated Brand brand) {
        String brandName = brand.getName();
        /*if (brandName == null|| brandName=="") {
            return AjaxResult.error("名称不能为空");
        }*/
        Brand one = brandService.getOne(Wrappers.lambdaQuery(Brand.class).eq(Brand::getName, brandName));
        if ((one != null) && (one.getId() != brand.getId())) {
            return AjaxResult.error("该品牌已经存在");
        }
        return toAjax(brandService.updateById(brand));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除品牌信息")
    public AjaxResult delete(@PathVariable("id") Long[] id) {
        boolean b = brandService.removeBatchByIds(Arrays.stream(id).toList());
        return toAjax(b);
    }
}
